package com.loongtech.bi.action.birealtime;

import com.loongtech.bi.action.TransferHelper;
import com.loongtech.bi.action.realTime.PlatformAndChannelRealTimeAction;
import com.loongtech.bi.entity.system.EntityBiChannel;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager.ChannelData;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager.ChannelHourData;
import com.loongtech.bi.manager.realTime.PlatformAndServerRealTimeManager.PlatformData;
import com.loongtech.bi.manager.system.BiPlatformManager;
import com.loongtech.bi.manager.system.SysRoleChannelManager;
import com.loongtech.bi.manager.system.SysUserManager;
import com.loongtech.bi.support.chart.ChartTool;
import com.loongtech.bi.support.chart.ChartUIData;
import com.loongtech.core.util.Time;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 
 * ClassName: PlatformAndChannelRealTimeBiAction
 * 
 * @Description: 实时数据-分渠道概况以及CPS概况
 * @author liuchen
 * @date 2017-5-23 下午2:28:41
 */
@Controller
@Scope("prototype")
@RequestMapping("/realTime/platformAndChannelRealTime")
public class PlatformAndChannelRealTimeBiAction extends TransferHelper {
	private static final long serialVersionUID = 1L;
	private ChartUIData channelOnlineRealTimeChart;
	private List<Map<Integer, String>> hourDatas;
	@Autowired
	PlatformAndServerRealTimeManager manager;

	private List<PlatformData> platformDatas;

	private PlatformData allPlatformData;

	private List<ChannelData> allChannelDatas;

	private List<ChannelData> channelDatas;

	private List<ChannelHourData> channelHourDatas;

	@Resource
	SysRoleChannelManager sysRoleChannelManager;

    @Autowired
    private SysUserManager sysUserManager;

	private List<PlatformAndServerRealTimeManager.ChannelOnlineRealTimeData> channelOnlineRealTimeDatas;

	@SuppressWarnings({ "serial" })
	private Map<Integer, String> hourMap = new HashMap<Integer, String>() {
		{
			put(0, "00:00~00:59");
			put(1, "01:00~01:59");
			put(2, "02:00~02:59");
			put(3, "03:00~03:59");
			put(4, "04:00~04:59");
			put(5, "05:00~05:59");
			put(6, "06:00~06:59");
			put(7, "07:00~07:59");
			put(8, "08:00~08:59");
			put(9, "09:00~09:59");
			put(10, "10:00~10:59");
			put(11, "11:00~11:59");
			put(12, "12:00~12:59");
			put(13, "13:00~13:59");
			put(14, "14:00~14:59");
			put(15, "15:00~15:59");
			put(16, "16:00~16:59");
			put(17, "17:00~17:59");
			put(18, "18:00~18:59");
			put(19, "19:00~19:59");
			put(20, "20:00~20:59");
			put(21, "21:00~21:59");
			put(22, "22:00~22:59");
			put(23, "23:00~23:59");
		}
	};

	/**
	 * 
	 * @Description: CPS查询
	 * @param @param request
	 * @param @param response
	 * @param @param date
	 * @param @param selectedPlatform
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "searchCps.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void searchCps(HttpServletRequest request, HttpServletResponse response, @RequestParam String date, @RequestParam String selectedPlatform, @RequestParam String uid, String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Date lookDate = Time.formatDate(date, "yyyy-MM-dd");

            Integer userid = sysUserManager.getUserIdByName(uid);
            if (null == userid) {
                result.put("res", 1);
                result.put("msg", "帐户错误，请联系管理员!");
                printToJson(response, result, callback);
                return;
            }

            platformDatas = new ArrayList<>();
			allPlatformData = manager.new PlatformData();
			allChannelDatas = new ArrayList<>();
			manager.updateDatas(lookDate, platformDatas, allPlatformData, allChannelDatas);
			if (!allPlatformData.isNotempty()) {
				allPlatformData = null;
			} else {
				selectPlatform(selectedPlatform);
			}
			List<ChannelData> list = getChannelDatasByUser(channelDatas, userid);
			for (ChannelData cd : list) {
				cd.setChannelid(BiPlatformManager.getChannelNameById(cd.getChannelid()));
			}
			result.put("res", "0");
			result.put("data", list);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	/**
	 * 
	 * @Description: 分渠道数据、渠道分小时数据数据
	 * @param @param request
	 * @param @param response
	 * @param @param date
	 * @param @param selectedPlatform
	 * @param @param selectZhiBiaoItem
	 * @param @param callback   
	 * @return void  
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "updateChannelData.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateChannelData(HttpServletRequest request, HttpServletResponse response, @RequestParam String date,
			@RequestParam String selectedPlatform, @RequestParam String selectZhiBiaoItem, String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			Date lookDate = Time.formatDate(date, "yyyy-MM-dd");
			platformDatas = new ArrayList<>();
			allPlatformData = manager.new PlatformData();
			allChannelDatas = new ArrayList<>();
			manager.updateDatas(lookDate, platformDatas, allPlatformData, allChannelDatas);
			selectPlatform(lookDate, selectZhiBiaoItem, selectedPlatform, allChannelDatas);
			List<ChannelData> list = getChannelDatasByUser(channelDatas, 0);
			for (ChannelData cd : list) {
				cd.setChannelid(BiPlatformManager.getChannelNameById(cd.getChannelid()));
			}
			for (ChannelHourData cd : channelHourDatas) {
				cd.setChannelid(BiPlatformManager.getChannelNameById(cd.getChannelid()));
			}
			result.put("res", "0");
			result.put("retlist", list);
			result.put("channelHourDatas", channelHourDatas);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	/**
	 * 
	 * @Description: 分渠道实时在线
	 * @param @param request
	 * @param @param response
	 * @param @param date
	 * @param @param channelItmes
	 * @param @param callback   
	 * @return void  
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "updateRealtimeChartData.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void updateRealtimeChartData(HttpServletRequest request, HttpServletResponse response,
			@RequestParam String date, @RequestParam String channelItmes, String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if ("".equals(channelItmes)) {
				result.put("res", "1");
				result.put("msg", "channelItmes is null");
				printToJson(response, result, callback);
				return;
			}
			List<String> selectedChannels = Arrays.asList(channelItmes.split(","));
			Date lookDate = Time.formatDate(date, "yyyy-MM-dd");
			channelOnlineRealTimeChart = null;
			channelOnlineRealTimeDatas = manager.getChannelOnlineRealTimeDatas(lookDate, selectedChannels);
			if (channelOnlineRealTimeDatas != null && channelOnlineRealTimeDatas.size() > 0) {
				channelOnlineRealTimeChart = new ChartUIData();
				channelOnlineRealTimeChart.setSelectItem("online");
				channelOnlineRealTimeChart.setJsonStr(new ChartTool(channelOnlineRealTimeDatas,
						PlatformAndServerRealTimeManager.ChannelOnlineRealTimeData.class, channelOnlineRealTimeChart
								.getSelectItem()).loadData(channelOnlineRealTimeChart.getJsonType()));
			} else {
				channelOnlineRealTimeChart = null;
			}
			result.put("res", "0");
			result.put("channelOnlineRealTimeChart", channelOnlineRealTimeChart);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	@SuppressWarnings("serial")
	private LinkedHashMap<String, String> allZhiBiaoItmes = new LinkedHashMap<String, String>() {
		{
			put("新增账号数", "newUser");
			put("付费账号数", "payUser");
			put("付费金额", "pay");
			put("新增账号付费人数", "newPayUser");
			put("新增账号付费金额", "newPay");
			put("新增账号付费金额", "newPay");
		}
	};

	@RequestMapping(value = "initParam.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void initParam(HttpServletRequest request, HttpServletResponse response, String callback) {
		try {
			Map<String, Object> result = new HashMap<String, Object>();
			List<EntityBiChannel> list = BiPlatformManager.CHANNEL_LIST;
			Map<String, String> channelItmes = new LinkedHashMap<>();
			for (int i = list.size() - 1; i >= 0; i--) {
				EntityBiChannel t = list.get(i);
				channelItmes.put(t.getName(), t.getId());
			}
			result.put("res", "0");
			result.put("channelItmes", channelItmes);
			result.put("allZhiBiaoItmes", allZhiBiaoItmes);
			printToJson(response, result, callback);
		} catch (Exception e) {
			e.printStackTrace();
			Map<String, Object> result = new HashMap<String, Object>();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
			return;
		}
	}

	/**
	 * 
	 * @Description: 分渠道概况
	 * @param @param request
	 * @param @param response
	 * @param @param date
	 * @param @param selectedPlatform
	 * @param @param callback
	 * @return void
	 * @throws
	 * @author liuchen
	 */
	@RequestMapping(value = "search.do", method = { RequestMethod.GET, RequestMethod.POST })
	public void search(HttpServletRequest request, HttpServletResponse response, @RequestParam String date,
			@RequestParam String selectedPlatform, @RequestParam String selectZhiBiaoItem,
			@RequestParam String channelItmes, String callback) {
		Map<String, Object> result = new HashMap<String, Object>();
		try {
			if ("".equals(channelItmes)) {
				result.put("res", "1");
				result.put("msg", "channelItmes is null");
				printToJson(response, result, callback);
				return;
			}
			List<String> selectedChannels = Arrays.asList(channelItmes.split(","));
			Date lookDate = Time.formatDate(date, "yyyy-MM-dd");
			platformDatas = new ArrayList<>();
			allPlatformData = manager.new PlatformData();
			allChannelDatas = new ArrayList<>();
			channelDatas = new ArrayList<>();
			hourDatas = new ArrayList<>();
			channelOnlineRealTimeChart = null;
			manager.updateDatas(lookDate, platformDatas, allPlatformData, allChannelDatas);
			if (!allPlatformData.isNotempty()) {
				allPlatformData = null;
			} else {

				channelOnlineRealTimeDatas = manager.getChannelOnlineRealTimeDatas(lookDate, selectedChannels);
				if (channelOnlineRealTimeDatas != null && channelOnlineRealTimeDatas.size() > 0) {
					channelOnlineRealTimeChart = new ChartUIData();
					channelOnlineRealTimeChart.setSelectItem("online");
					channelOnlineRealTimeChart.setJsonStr(new ChartTool(channelOnlineRealTimeDatas,
							PlatformAndServerRealTimeManager.ChannelOnlineRealTimeData.class,
							channelOnlineRealTimeChart.getSelectItem()).loadData(channelOnlineRealTimeChart
							.getJsonType()));
				} else {
					channelOnlineRealTimeChart = null;
				}
				selectPlatform(lookDate, selectZhiBiaoItem, selectedPlatform, allChannelDatas);
			}

			List<ChannelData> list = getChannelDatasByUser(channelDatas, 0);
			for (ChannelData cd : list) {
				cd.setChannelid(BiPlatformManager.getChannelNameById(cd.getChannelid()));
			}
			for (ChannelHourData cd : channelHourDatas) {
				cd.setChannelid(BiPlatformManager.getChannelNameById(cd.getChannelid()));
			}
			for (PlatformData cd : platformDatas) {
				cd.setPlatformid(BiPlatformManager.getPlatformNameById(cd.getPlatformid()));
			}
			result.put("res", "0");
			result.put("retlist", list);
			result.put("platformDatas", platformDatas);
			result.put("allPlatformData", allPlatformData);
			result.put("channelHourDatas", channelHourDatas);
			result.put("channelOnlineRealTimeChart", channelOnlineRealTimeChart);
			printToJson(response, result, callback);

		} catch (Exception e) {
			e.printStackTrace();
			result.put("res", "1");
			result.put("msg", e.getMessage());
			printToJson(response, result, callback);
		}
	}

	private void selectPlatform(String selectedPlatform) {
		channelDatas = new ArrayList<>();
		if (allChannelDatas != null && allChannelDatas.size() > 0) {
			if ("all".equals(selectedPlatform)) {
				channelDatas = allChannelDatas;
				Collections.sort(channelDatas, manager.new ChannelData().comparator2);
			} else {
				for (ChannelData c : allChannelDatas) {
					String pid = BiPlatformManager.CHANNEL_PLATFORM_MAP.get(c.getChannelid());
					if (pid != null && pid.equals(selectedPlatform)) {
						channelDatas.add(c);
					}
				}
				Collections.sort(channelDatas, manager.new ChannelData().comparator);
			}
		}
	}

	public void selectPlatform(Date lookDate, String selectZhiBiaoItem, String selectedPlatform,
			List<ChannelData> allChannelDatas) {
		channelDatas = new ArrayList<>();
		if (allChannelDatas != null && allChannelDatas.size() > 0) {
			if ("all".equals(selectedPlatform)) {
				channelDatas = allChannelDatas;
				Collections.sort(channelDatas, manager.new ChannelData().comparator2);
			} else {
				for (ChannelData c : allChannelDatas) {
					String pid = BiPlatformManager.CHANNEL_PLATFORM_MAP.get(c.getChannelid());
					if (pid != null && pid.equals(selectedPlatform)) {
						channelDatas.add(c);
					}
				}
				Collections.sort(channelDatas, manager.new ChannelData().comparator);
			}
			getChannelDatasByUser(channelDatas, 0);
		}
		handleZhiBiaoChange(lookDate, selectZhiBiaoItem, selectedPlatform);
	}

	public void handleZhiBiaoChange(Date lookDate, String selectZhiBiaoItem, String selectedPlatform) {
		channelHourDatas = new ArrayList<>();
		hourDatas = new ArrayList<>();
		manager.updateChannelHourDatas(lookDate, selectZhiBiaoItem, selectedPlatform, channelHourDatas);

		Set<Integer> t = new HashSet<>(); // 用于补齐数据
		for (ChannelHourData s : channelHourDatas) {
			hourDatas.add(s.getDatas());
			for (int i : s.getDatas().keySet()) {
				t.add(i);
			}
		}
		for (Map<Integer, String> h : hourDatas) {
			for (int tt : t) {
				if (h.get(tt) == null) {
					h.put(tt, "");
				}
			}
			sortMapByKey(h);
		}
	}

	public String getHourStr(int hour) {
		if (hour < 0 || hour > 23) {
			return "";
		}
		return hourMap.get(hour);
	}

	public static void sortMapByKey(Map<Integer, String> map) {
		if (map == null || map.isEmpty()) {
			return;
		}
		Map<Integer, String> sortMap = new TreeMap<Integer, String>(
				new PlatformAndChannelRealTimeAction().new MapKeyComparator());
		sortMap.putAll(map);
		map.clear();
		map.putAll(sortMap);
	}

	public List<ChannelData> getChannelDatasByUser(List<ChannelData> allChannelDatas, int userid) {
		List<ChannelData> retlist = new ArrayList<>();
		List<ChannelData> allList = allChannelDatas;
		Set<String> selectedSet = sysRoleChannelManager.getChannelSetByUserId(userid);
		/*
		 * if (null == selectedSet || selectedSet.isEmpty() || null == allList
		 * || allList.isEmpty()) { return null; }
		 */

		if (selectedSet.size() > 0 && allChannelDatas != null && allChannelDatas.size() > 0) {
            for (ChannelData info : allList) {
                if (selectedSet.contains(info.getChannelid())) {
                    retlist.add(info);
                }
            }
        }

		return retlist;
	}
}
